<template>
	<view class="cart-container">
		<shopNavbar :showup="showup" :pageTitle="shopName" @handleBack="goback" :isAdmin="isAdmin"></shopNavbar>
		<view class="cart-popup" :style="{ marginTop: navBarHeight + 'rpx' }" @touchmove.stop.prevent="preventScroll">
			<view class="cart-header">
				<view class="header-txt" @click="navtoShop">
					<uni-icons type="shop" size="26"></uni-icons>
					<text>商城</text>
				</view>
				<view class="header-txt" @click="orderList">
					<uni-icons type="wallet" size="26"></uni-icons>
					<text>历史订单</text>
				</view>
				<view class="header-txt" @click="clearCart">
					<uni-icons type="trash" size="26"></uni-icons>
					<text>清空</text>
				</view>
			</view>

			<scroll-view class="cart-list" scroll-y @touchmove.stop="preventScroll">
				<view v-for="item in items" :key="item.productId" class="cart-item">
					<image :src="item.images[0].url" class="item-image" @click="navigateToDetail(item)" />
					<view class="item-info">
						<text class="title">{{ item.productName }}</text>
						<text class="price">¥{{ item.price }}</text>
					</view>
					<view class="quantity-control">
						<text class="btn minus" @click="changeQuantity(item, -1)">-</text>
						<text class="quantity">{{ item.quantity }}</text>
						<text class="btn plus" @click="changeQuantity(item, 1)">+</text>
					</view>
				</view>
				<u-empty v-if="items.length===0"
				        mode="car"
				       
				>
				</u-empty>
				<view class="entry-shop" @click="entryShop">
					<uni-icons type="shop" size="28" color="#55aaff"></uni-icons>
					<text>进入商城继续选购</text>
				</view>
			</scroll-view>
		</view>
		<view class="cart-footer">
			<text class="total">合计：¥{{ total }}</text>

			<view class="cart-foot-txt" @touchend.prevent="handerIsSend">
				<checkbox v-model="isSend" :checked="!isSend" />
				<text>管家结算</text>
			</view>

			<button class="checkout-btn" :disabled="items.length === 0" @click="checkout">{{ isSend ? '去结算' : '下单' }}</button>
		</view>

		<movable-area
			:style="{
				width: windowWidth + 'px',
				height: windowHeight + 'px',
				position: 'fixed',
				top: 0,
				left: 0,
				right: 0,
				bottom: 0,
				zIndex: 9999,
				pointerEvents: 'none'
			}"
		>
			<movable-view direction="all" style="pointer-events: auto" x="500" y="800">
				<RightBar type="shop" :bottom="150 + 'rpx'"></RightBar>
			</movable-view>
		</movable-area>
		<template>
			<view class="popup-container" v-if="showPopup">
				<view class="popup-mask" @click="closePopup"></view>

				<view class="popup-content">
					<order-sure @closePopup="closePopup" ></order-sure>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
import shopNavbar from '../../components/shopNavbar.vue';
import RightBar from '../../components/RightBar.vue';
import orderSure from '@/components/orderSure.vue';
const order = uniCloud.importObject('order', {
	customUI: false
});

export default {
	components: {
		shopNavbar,
		RightBar,
		orderSure
	},

	data() {
		return {
			isSend: true,
			user: null,
			showup: true,
			shopName: '',
			windowHeight: 0,
			windowWidth: 0,
			navBarHeight: 220,
			isAdmin: false,
			showPopup: false,
			
		};
	},
	computed: {
		items() {
			return this.$store.state.cart.items || [];
		},
		total() {
			return this.$store.state.cart.total || 0;
		},
		totalCount() {
			return this.$store.getters['cart/totalCount'] || 0;
		},
		storeData() {
			return this.$store.state.msg;
		},
		lastAddress(){
			return uni.getStorageSync('lastAddress')||{}
		}
	},
	watch: {
		items: {
			handler(newval) {
				console.log('cart', newval);
			}
		}
	},
	mounted() {
		try {
			const res = this.$store.state.msg.systemInfo;
			this.windowHeight = res.windowHeight;
			this.windowWidth = res.windowWidth;
		    
		} catch (e) {
			console.error('获取设备信息失败：', e);
		}
	},
	methods: {
		preventScroll(e) {
			// 关键：只在事件可取消时调用 preventDefault()，避免无效操作触发警告
			if (e.cancelable) {
				e.preventDefault();
			}
			// 阻止事件冒泡到父容器，避免带动页面背景滚动
			e.stopPropagation();
		},
		navtoShop() {
			uni.navigateTo({
				url: '/pages/shop/shop'
			});
		},
		closePopup() {
			this.showPopup = false;
		},
		handerIsSend() {
			this.isSend = !this.isSend;
		},
		navigateToDetail(product) {
			const formated = encodeURIComponent(JSON.stringify(product));
			uni.navigateTo({
				url: `/pages/goodDetail/goodDetail?product=${formated}`
			});
		},
		getQuantity(productId) {
			const items = this.$store?.state?.cart?.items || [];
			const item = items.find((item) => item._id === productId);
			return item?.quantity || 0;
		},
		changeQuantity(item, delta) {
			uni.vibrateShort({});
			const currentQty = this.getQuantity(item._id);

			if (currentQty === 0) {
				// 新增商品到购物车
				this.$store.commit('cart/addItem', { ...item, quantity: 1 });
			} else {
				const newQty = currentQty + delta;
				if (newQty > 0) {
					// 更新数量
					this.$store.commit('cart/updateQuantity', {
						id: item._id,
						quantity: newQty
					});
				} else {
					// 移除商品
					this.$store.commit('cart/removeItem', item._id);
				}
			}
		},
		entryShop() {
			uni.navigateTo({
				url: '/pages/shop/shop'
			});
		},
		goback() {
			uni.navigateBack();
		},
		clearCart() {
			const _this = this;
			uni.showModal({
				title: '确认清空购物车？',
				success(res) {
					if (res.confirm) {
						_this.$store.commit('cart/clearCart');
						uni.navigateBack();
					}
				}
			});
		},
		orderList() {
			uni.navigateTo({
				url: '/pages/orderList/orderList'
			});
		},
		async checkout() {
			this.showPopup = true;
			// uni.navigateTo({
			// 	url:'/pages/orderSure/orderSure'
			// })
			// if (this.items.length === 0) {
			// 	uni.showToast({
			// 		title: '无订单'
			// 	});
			// 	return;
			// }
			// if (!this.storeData?.user?.userId) {
			// 	uni.showToast({ title: '订单参数缺失，请重试', icon: 'none' });
			// 	return;
			// }

			// uni.showLoading({
			// 	title: '订单正在提交...'
			// });
			// const _this = this;
			// console.log('items: ' + JSON.stringify(this.items));

			// const orderData = {
			// 	userId: this.storeData.user.userId,
			// 	productList: this.items,
			// 	addressId: '123'
			// };

			// const data = await order.createOrder(orderData);
			// console.log('下单结果', data);
			// if (data.success) {
			// 	uni.hideLoading();
			// 	uni.showModal({
			// 		title: data.message,
			// 		content: `订单号：${data.orderId}`,
			// 		success(res) {
			// 			console.log(res);
			// 			if (res.confirm) {
			// 				_this.$store.commit('cart/clearCart');
			// 				uni.navigateTo({
			// 					url: '/pages/orderList/orderList'
			// 				});
			// 			}
			// 		}
			// 	});
			// } else {
			// 	uni.hideLoading();
			// 	uni.showModal({
			// 		title: '下单失败',
			// 		content: `${data.message}`
			// 	});
			// }
		}
	}
};
</script>
<style lang="scss" scoped>
.cart-container {
}

.cart-icon {
	position: fixed;
	right: 40rpx;
	bottom: 200rpx;
	width: 100rpx;
	height: 100rpx;
	background-color: #ccc;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: #333;
	box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
	z-index: 99;
}
.header-txt {
	font-size: 26rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	:active {
		color: #007aff;
	}
}
.cart {
	position: relative;
	width: 100rpx;
	height: 100rpx;
}
.badge {
	position: absolute;
	top: 1rpx;
	left: 0;
}

.cart-popup {
	background: #fff;
	max-height: 80vh;
	border-radius: 24rpx 24rpx 0 0;
	display: flex;
	flex-direction: column;
	z-index: 99999;
	pointer-events: auto;
}

.cart-header {
	display: flex;
	justify-content: space-between;
	padding: 15rpx 30rpx;
	font-size: 32rpx;
	background-color: #f5f5f5;
	border-bottom: 1rpx solid #f1f1f1;
}

.cart-list {
	flex: 1;
	pointer-events: auto;
	overflow: hidden;
	padding: 0 30rpx;
	overflow-y: auto;
	padding-bottom: 50rpx;
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 10rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.item-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 16rpx;
	margin-right: 30rpx;
	flex-shrink: 0;
}

.item-info {
	flex: 1;
	min-width: 0;
}

.title {
	font-size: 28rpx;
	line-height: 1.5;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.price {
	font-size: 36rpx;
	color: #e64340;
	font-weight: bold;
	margin-top: 15rpx;
}

.quantity-control {
	display: flex;
	align-items: center;
	margin-left: 30rpx;
	margin-right: 50rpx;
}

.btn {
	width: 50rpx;
	height: 50rpx;
	line-height: 50rpx;
	text-align: center;
	border-radius: 50%;
	font-size: 36rpx;
	font-weight: bolder;
}

.btn::after {
	content: '';

	top: -10rpx;
	right: -10rpx;
	bottom: -10rpx;
	left: -10rpx;
}

.plus {
	background: #007aff;
	color: white;
}

.minus {
	border: 2rpx solid #007aff;
	color: #007aff;
}

.quantity {
	margin: 0 20rpx;
	min-width: 40rpx;
	text-align: center;
	font-size: 32rpx;
}

.cart-footer {
	position: fixed;
	bottom: 0;
	gap: 25rpx;
	width: 750rpx;
	background: #f1f1f1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15rpx 30rpx;
	padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
	box-shadow: 0 4rpx 5rpx rgba(0, 0, 0, 0.05);
	z-index: 10;
	.cart-foot-txt {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
	}
}

.total {
	font-size: 32rpx;
	color: #00aa00;
	font-weight: bold;
}

.checkout-btn {
	background: linear-gradient(90deg, #007aff, #00aaff);
	color: white;
	border-radius: 50rpx;
	padding: 0 60rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.cart-popup {
	background: #fff;
	// 移除 margin-top: 230rpx，改用动态 top 定位

	flex: 1; // 占满容器剩余高度
	border-radius: 24rpx 24rpx 0 0;
	display: flex;
	flex-direction: column;
	pointer-events: auto;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
}
.entry-shop {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-left: auto;
	margin-right: auto;
	margin-top: 50rpx;
	width: 350rpx;
	min-height: 40rpx;
	font-size: 32rpx;
	padding: 5rpx 10rpx;
	border-radius: 20rpx;
	
	color: #55aaff;
	margin-top: 10rpx;
}
.popup-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 999;
}
.popup-content {
	position: fixed;
	top: 10%; /* 顶部留 10% 空白，居中 */
	left: 50%;
	transform: translateX(-50%);
	width: 90%; /* 宽度 90% 屏幕，留边距 */
	height: 80%; /* 固定高度！关键 */
	background-color: #fff;
	border-radius: 24rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
	z-index: 1000;
	overflow: hidden; /* 禁止 Popup 自身滚动，仅内部内容滚动 */
}
</style>
